using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Text.RegularExpressions;
using MCromwell.StaffIntranet.Presenters;

namespace MCromwell.StaffIntranet.UI
{
    public class StaffPhotoHandler : IHttpHandler
    {
        StaffPhotoPresenter presenter;
        HttpResponse response;
        byte[] defaultImageData;

        public StaffPhotoHandler()
        {
            InitializePresenter();

            defaultImageData = File.ReadAllBytes(ConfigurationManager.AppSettings["default-photo-path"]);
        }

        private void InitializePresenter()
        {
            presenter = new StaffPhotoPresenter();
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            response = context.Response;
            string rawId = Regex.Match(context.Request.Url.LocalPath, @"(?<id>\d+).photo").Groups["id"].Value;
            if (!ValidStaffIdPassed(rawId))
            {
                int id = -1;
                if (CanConvertToInteger(rawId, ref id))
                {
                    byte[] imageData = presenter.RetrievePhotoFor(id);
                    if (ValidImageForStaffReturned(imageData))
                        WriteImageResponse(imageData);
                    else
                        WriteImageResponse(defaultImageData);
                }
                else
                    WriteImageResponse(defaultImageData);
            }
            else
            {
                WriteImageResponse(defaultImageData);
            }
        }

        private static bool ValidImageForStaffReturned(byte[] imageData)
        {
            if ((imageData == null) || (imageData.Length <= 0))
                return false;

            try
            {
                using (System.Drawing.Image actualImage = System.Drawing.Image.FromStream(new MemoryStream(imageData)
                                                                                    , false
                                                                                    , true))
                {
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private static bool CanConvertToInteger(string rawId, ref int id)
        {
            return int.TryParse(rawId, out id);
        }

        private static bool ValidStaffIdPassed(string rawId)
        {
            return string.IsNullOrEmpty(rawId);
        }
               
        private void WriteImageResponse(byte[] imageData)
        {
            response.ContentType = "image/jpeg";
            response.Cache.SetExpires(DateTime.MinValue);
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.BinaryWrite(imageData);
            response.Flush();
        }
    }
}
